package cn.sciento.farm.devicemanager.gateway.lorawan.grpc.impl;

import cn.sciento.farm.devicemanager.gateway.lorawan.config.JwtManager;
import cn.sciento.farm.devicemanager.gateway.lorawan.grpc.DeviceProfileService;
import cn.sciento.farm.devicemanager.gateway.lorawan.grpc.GrpcConstant;
import cn.sciento.farm.devicemanager.lorawan.*;
import io.grpc.Channel;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wumu
 * @version V1.0
 * @date 9/17/18
 * @time 9:46 AM
 */
@Service
public class DeviceProfileServiceImpl implements DeviceProfileService {

    @GrpcClient(GrpcConstant.GRPC_NAME)
    private Channel serverChannel;


    @Autowired
    private JwtManager jwtManager;

    volatile DeviceProfileServiceGrpc.DeviceProfileServiceBlockingStub stub;


    DeviceProfileServiceGrpc.DeviceProfileServiceBlockingStub getStub() {
        if (stub == null) {
            synchronized (DeviceProfileServiceImpl.class) {
                if (stub == null) {
                    stub = DeviceProfileServiceGrpc.newBlockingStub(serverChannel);
                }
            }
        }
        stub = stub.withCallCredentials(jwtManager.getToken());
        return stub;
    }

    @Override
    public CreateDeviceProfileResponse create(CreateDeviceProfileRequest request) {
        return getStub().create(request);
    }

    @Override
    public GetDeviceProfileResponse get(GetDeviceProfileRequest request) {
        return getStub().get(request);
    }

    @Override
    public void update(UpdateDeviceProfileRequest request) {
        getStub().update(request);
    }

    @Override
    public void delete(DeleteDeviceProfileRequest request) {
        getStub().delete(request);
    }

    @Override
    public ListDeviceProfileResponse list(ListDeviceProfileRequest request) {
        return getStub().list(request);
    }
}
